<?php
/**
 * 微信商户平台
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/7/17
 * @copyright PanxSoft Inc.
 */

namespace App\Services\OpenWechat;

use App\Models\OpenWechat\WechatUser;
use App\Models\Panx\SkinRecordBonus;
use App\Services\Utils\TimeHelper;
use EasyWeChat\Factory;

use App\Models\OpenWechat\Authorizer;

class MerchantPay
{
    CONST RET_SUCCESS = "SUCCESS";

    protected $payment;
    /**
     * @var Authorizer
     */
    private $authorizer;

    /**
     * MaterialSave constructor.
     * @param Authorizer $authorizer
     * @throws \Exception
     */
    public function __construct(Authorizer $authorizer)
    {
        $this->authorizer = $authorizer;

        $this->payment = Factory::payment($this->paymentConfig());
    }

    /**
     * @return array
     */
    private function paymentConfig(): array
    {
        $author = isset($this->authorizer->merchant_id)
            ? $this->authorizer
            : Authorizer::defaultMerchant();

        /**
         * @link https://www.easywechat.com/docs/master/zh-CN/payment/index - 参数参考
         */
        return [
            'app_id'    => $author->authorizer_appid,
            'mch_id'    => $author->merchant_id,
            'key'       => $author->merchant_key,
            'cert_path' => app_path("certs/wechat/merchants/{$author->merchant_id}/apiclient_cert.pem"),
            'key_path'  => app_path("certs/wechat/merchants/{$author->merchant_id}/apiclient_key.pem"),

            // 只有 payment -> pay 支付类才能使用沙箱，转账红包是不能用的
            'sandbox'   => config('pkx.open_wechat.pay_sandbox')
        ];
    }

    /**
     * 企业支付到用户零钱
     * @test
     *
     * @param array $config
     *
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function transferToBalance(array $config = []): array
    {
        /**
         * @link https://www.easywechat.com/docs/master/zh-CN/payment/transfer - 参数参考
         */
        $result = $this->payment->transfer->toBalance($config + $this->descriptionConfig());

        return $result;
    }

    /**
     * 刷卡支付 - WIP
     *
     * @link https://mp.weixin.qq.com/s/Z69r1OpbMarPkQJbGBYlCg - 只有指定金额才能触发沙箱测试
     */
    public function cardPay(): array
    {
        $result = $this->payment->pay([
            'body' => '沙箱测试',
            'out_trade_no' => TimeHelper::microTimeSerial(),
            'total_fee' => 1,
            'auth_code' => '120061098828009406',
        ]);

        return $result;
    }


    /**
     * @param SkinRecordBonus $skinRecordBonus
     * @return array
     * @throws \Exception
     */
    public function transferToBalanceForSkinRecordBonus(SkinRecordBonus $skinRecordBonus): array
    {
        $openid = class_basename($skinRecordBonus->bonusable) === class_basename(WechatUser::class)
            ? $skinRecordBonus->bonusable->openid
            : $skinRecordBonus->bonusable->wechatUser->openid;

        $result = $this->payment->transfer->toBalance([
            'partner_trade_no' => TimeHelper::microTimeSerial(), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid'           => $openid, // zeon openid
            'check_name'       => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name'     => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount'           => (int) ($skinRecordBonus->amount * 100), // 企业付款金额，单位为分
            'desc'             => $skinRecordBonus->getWxTransferPayDescription(), // 企业付款操作说明信息。必填
        ]);

        return $result;
    }

    /**
     * 参考配置
     *
     * @return array
     */
    protected function descriptionConfig(): array
    {
        return [
            'partner_trade_no' => TimeHelper::microTimeSerial(), // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid'           => '这里必须提供正确的属于公众号的openid',
            'check_name'       => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name'     => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount'           => 100, // 企业付款金额，单位为分
            'desc'             => '必填企业付款操作说明信息',
        ];
    }
}   